package de.slothsoft.commons.swing;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import de.slothsoft.commons.swing.util.JTableUtil;

public final class TableCreatorUtil {

	public static final <T> JTable buildTable(final ITableCreator<T> holder,
			JPanel mainPanel) {
		mainPanel.setLayout(new BorderLayout());

		// create top component

		Component filterComponent = holder.createFilterComponent();
		if (filterComponent != null) {
			mainPanel.add(filterComponent, BorderLayout.NORTH);
		}

		// create center / table component

		JTable table = JTableUtil.createTable(holder.createModel(),
				holder.createColumnWidths(), holder.createRenderer());
		hookListeners(holder, table);
		mainPanel.add(new JScrollPane(table), BorderLayout.CENTER);

		// create bottom component

		Component informationComponent = holder.createInformationComponent();
		if (informationComponent != null) {
			mainPanel.add(informationComponent, BorderLayout.SOUTH);
		}

		return table;
	}

	private static <T> void hookListeners(final ITableCreator<T> holder,
			JTable table) {
		JTableUtil.addSelectionListener(table, new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				holder.performSelectionChanged();
			}
		});
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getButton() == MouseEvent.BUTTON1
						&& e.getClickCount() == 2) {
					holder.performDoubleClick();
				}
			}
		});
	}

	private TableCreatorUtil() {
		// *hide*
	}

}
